package com.ruoyi.auth.service;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.shaded.com.google.gson.JsonObject;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.constant.UserConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.RemoteWxUserService;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.factory.RemoteFileFallbackFactory;
import com.ruoyi.system.api.model.LoginWxUser;
import com.yxzz.core.domain.TUser;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class WxUserService {

    private static final Logger log = LoggerFactory.getLogger(WxUserService.class);


    @Autowired
    private SysRecordLogService recordLogService;

    @Autowired
    private RedisService redisService;


    @Autowired
    private RemoteWxUserService remoteWxUserService;


    private final static String MALL_FRONT_DOMAIN = "https://api.it120.cc/yxzz";
    private final static String MALL_BACK_DOMAIN = "https://user.api.it120.cc";
    private final static String MOBILE = "13824409838";
    private final static String PWD = "qwe,./123";
    public boolean checkMallTokenExpired(String token){
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("token", token);

        String result = HttpUtil.get(MALL_FRONT_DOMAIN+"/user/check-token", paramMap);
        if (StringUtils.isEmpty(result)) {
            return true;
        }
        JSONObject jsonObject = JSONObject.parseObject(result);
        String code = jsonObject.getString("code");
        switch (code){
            case "0":
                return false;
            default:
                return true;
        }
    }

    public LoginWxUser getUser(String openId){
        R<LoginWxUser> userResult = remoteWxUserService.getInfoByOpenId(openId,  SecurityConstants.INNER);

        if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData()))
        {
            return null;
        }

        if (R.FAIL == userResult.getCode())
        {
            throw new ServiceException(userResult.getMsg());
        }

        LoginWxUser loginWxUser = userResult.getData();
        return loginWxUser;
    }

    private String getTokenCacheKey(){
        return "MALL::ADMIN::TOKENID";
    }


    public String loginToMallAdmin(){
        String lockKey = "loginToMallAdminLock";
        Long value = System.currentTimeMillis();
        Boolean islock = redisService.redisTemplate.opsForValue().setIfAbsent(lockKey, value, Duration.ofMillis(60 * 1000));
        try {
            if (islock) {
                Map<String, Object> paramMap = new HashMap<>();
                paramMap.put("mobile", MOBILE);
                paramMap.put("pwd", PWD);

                String result = HttpUtil.post(MALL_BACK_DOMAIN + "/login/mobile/v2", paramMap);
                JSONObject jsonObject = JSONObject.parseObject(result);
                jsonObject = jsonObject.getJSONObject("data");
                String token = jsonObject.getString("token");
                // set to redis
                redisService.setCacheObject(getTokenCacheKey(), token, 2L, TimeUnit.DAYS);
                return token;
            }
        }catch (Exception e){
            log.info("get lock exception,", e);
        }finally {
            Object currentValue = redisService.redisTemplate.opsForValue().get(lockKey);
            if (currentValue != null && currentValue.equals(value)) {
                redisService.redisTemplate.delete(lockKey);
            }
        }
        return null;
    }

    private String getMallAdminToken(){
        String token = redisService.getCacheObject(getTokenCacheKey());
        if (StringUtils.isEmpty(token)){
            token = loginToMallAdmin();
        }
        return token;
    }

    public JSONObject getUserDetailsFromMall(String mallUserId){
        String token = getMallAdminToken();
        String result = HttpRequest.get(MALL_BACK_DOMAIN + "/user/apiExtUser/info?id="+mallUserId)
                .header("X-Token", token)
                .execute().body();
        JSONObject jsonObject = JSONObject.parseObject(result);
        switch (jsonObject.getString("code")){
            case "100000":
                redisService.deleteObject(getTokenCacheKey());
                return getUserDetailsFromMall(mallUserId);
            default:
                break;
        }
        return jsonObject.getJSONObject("data");
    }

    /**
     * 注册
     */
    public void register(JSONObject jsonObject)
    {
        JSONObject userBase = jsonObject.getJSONObject("userBase");
        String username = userBase.getString("id");
        String phoneNumber = userBase.getString("mobile");
        String nickName = userBase.getString("nick");

        JSONObject userBaseWx = jsonObject.getJSONObject("userBaseWx");
        String openId = userBaseWx.getString("openid");
        // 注册用户信息
        TUser tUser = new TUser();
        tUser.setUserName(username);
        tUser.setNickName(nickName);
        tUser.setPhonenumber(phoneNumber);
        tUser.setOpenId(openId);
        R<?> registerResult = remoteWxUserService.registerUserInfo(tUser, SecurityConstants.INNER);

        if (R.FAIL == registerResult.getCode())
        {
            throw new ServiceException(registerResult.getMsg());
        }
        recordLogService.recordLogininfor(tUser.getUserName(), Constants.REGISTER, "注册成功");
    }


}
